package org.ricks.condition2;

import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.function.BiConsumer;

/**
 * 绑定条件完成后续业务执行， 比如：接取任务 - 完成任务推送 -
 */
public class ConditionBinder {
    private static class SingletonHolder {
        private static final ConditionBinder INSTANCE = new ConditionBinder();
    }

    private final Map<Condition, List<BiConsumer<String, Condition>>> bindings = new ConcurrentHashMap<>();

    public static ConditionBinder getInstance() {
        return SingletonHolder.INSTANCE;
    }

    public void bind(Condition condition, BiConsumer<String, Condition> handler) {
        bindings.computeIfAbsent(condition, k -> new CopyOnWriteArrayList<>()).add(handler);
    }

    public void unbind(Condition condition) {
        bindings.remove(condition);
    }

    public List<BiConsumer<String, Condition>> getHandlers(Condition condition) {
        return bindings.getOrDefault(condition, Collections.emptyList());
    }
}
